<template>
  <div class="call-history-container">
    <h1>通讯记录查询</h1>
    <div class="operation-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入主叫号、被叫号关键词搜索"
        style="width: 300px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="exportTemplate">导出模板</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 15px;"
      v-loading="loading"
    >
      <!-- 修正：匹配接口返回的historyId字段 -->
      <el-table-column prop="historyId" label="记录ID" width="120" />
      <el-table-column prop="userName" label="拨打用户" />
      <el-table-column prop="bill" label="话费" />
      <el-table-column prop="callingNumber" label="主叫号" />
      <el-table-column prop="calledNumber" label="被叫号" />
      <!-- 修正：时长字段为time，添加单位转换 -->
      <el-table-column label="通讯时长(秒)">
        <template #default="scope">
          {{ scope.row.time || 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="计费状态">
        <template #default="scope">
          <span :class="scope.row.status === 1 ? 'success' : 'warning'">
            {{ scope.row.status === 1 ? '已计费' : '未计费' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="开始时间" width="180" />

      <el-table-column prop="updateTime" label="结束时间" width="180" />
    </el-table>

    <!-- 分页区 -->
    <div class="pagination-bar" v-if="total > 0">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { gethistoryPageAPI, searchhistoryAPI } from '@/apis/bill';

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');
const loading = ref(false);

// 初始化页面加载数据
onMounted(() => {
  fetchHistoryList();
});

// 获取列表数据（重点修正数据处理逻辑）
const fetchHistoryList = async () => {
  try {
    loading.value = true;
    const response = await gethistoryPageAPI(currentPage.value);
    console.log("接口返回原始数据:", response); // 用于调试

    if (response.code === 0) {
      // 1. 处理分页数据结构（根据实际返回调整）
      const responseData = response.data || {};
      // 2. 兼容列表数据可能直接在data中或data.records中
      tableData.value = responseData.records || responseData || [];
      // 3. 处理总条数
      total.value = responseData.total || tableData.value.length;
      pageSize.value = responseData.size || 10;
    } else {
      ElMessage.warning('暂无通讯记录数据');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取通讯记录失败:', error);
    ElMessage.error('获取通讯记录失败');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索功能（同步修正数据处理）
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    fetchHistoryList();
    return;
  }

  try {
    loading.value = true;
    const response = await searchhistoryAPI(searchKeyword.value);
    console.log("搜索返回数据:", response);

    if (response.code === 0) {
      tableData.value = response.data || [];
      total.value = tableData.value.length;
    } else {
      ElMessage.warning('未搜索到匹配记录');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('搜索通讯记录失败:', error);
    ElMessage.error('搜索通讯记录失败');
  } finally {
    loading.value = false;
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchHistoryList();
};

// 引入Element组件
const { proxy } = getCurrentInstance();
const ElMessage = proxy.$message;

// 导出模板功能
const exportTemplate = () => {
  const link = document.createElement('a');
  link.href = '/api/cms/virtualphone/exportTemplate';
  link.download = '虚拟电话号码信息模板.xls';
  link.click();
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.call-history-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.operation-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.pagination-bar {
  margin-top: 15px;
  text-align: right;
}

.success {
  color: #10b981;
}

.warning {
  color: #f59e0b;
}
</style>
